package club.babyf.nativeai.demo.algorithm;

/**
 * ReverseAfterNthNode.
 *
 * @author zhanglei.
 * @date 2025/5/8 16:28.
 * @description 根据传入的节点反转节点之后的链表.
 */
public class _6_ReverseAfterNthNode {

    public ListNode reverseAfterNthNode(ListNode head, int n) {
        if (head == null || n < 0) {
            return head;
        }

        // 使用虚拟头节点简化操作
        ListNode dummy = new ListNode(-1);
        dummy.next = head;
        ListNode pre = dummy;

        // 移动pre到第n个节点
        for (int i = 0; i < n; i++) {
            if (pre.next == null) {
                // n超过链表长度，直接返回原链表
                return dummy.next;
            }
            pre = pre.next;
        }

        // 反转后续部分
        ListNode subHead = pre.next;
        if (subHead == null) {
            // 无需反转
            return dummy.next;
        }

        ListNode newSubHead = reverseList(subHead);
        // 连接反转后的链表
        pre.next = newSubHead;

        return dummy.next;
    }

    // 反转链表标准实现
    private ListNode reverseList(ListNode head) {
        ListNode prev = null;
        ListNode curr = head;
        while (curr != null) {
            ListNode nextTemp = curr.next;
            curr.next = prev;
            prev = curr;
            curr = nextTemp;
        }
        return prev;
    }

    public static void main(String[] args) {
        ListNode head = new ListNode(1, new ListNode(2, new ListNode(3, new ListNode(4, new ListNode(5)))));
        System.out.println(head);
        _6_ReverseAfterNthNode reverseAfterNthNode = new _6_ReverseAfterNthNode();
        ListNode reversedList = reverseAfterNthNode.reverseAfterNthNode(head, 2);
        System.out.println(reversedList);
    }

    public static class ListNode {

        int value;

        ListNode next;

        ListNode() {

        }

        ListNode(int value) {
            this.value = value;
        }

        ListNode(int value, ListNode next) {
            this.value = value;
            this.next = next;
        }

        public String toString() {
            StringBuilder sb = new StringBuilder();
            ListNode current = this;
            while (current != null) {
                sb.append(current.value);
                ListNode next = current.next;
                if (next != null) {
                    sb.append(" -> ");
                }
                current = next;
            }
            return sb.toString();
        }

    }

}
